<template>
  <!--非接触受理-->
  <div v-loading="loadPdf" class="noTouch-containers" :style="{ height }">
    <!-- <div v-if="loadPdf" class="pop-container" /> -->
    <div class="evid-l">
      <!-- <el-radio-group v-model="tabValue" style="margin-bottom: 10px" @change="tabChange">
        <el-radio-button label="file">文书列表</el-radio-button>
        <el-radio-button label="evidence">证据材料</el-radio-button>
      </el-radio-group> -->
      <div class="evid-wrap">
        <div class="evid-type receive-costTitle">文件列表</div>
        <div class="evid-box">
          <template v-if="tabValue === 'file'">
            <div
              v-for="(treeDoc) in documentTree"
              :key="treeDoc.treeId"
              class="evid-con"
            >
              <div class="evid-first">
                <div v-if="treeDoc.treeDocList && treeDoc.treeDocList.length" class="tree-check-icon" :class="{'active' : treeDoc.checked}" @click.stop="handleFirstNameCheck(treeDoc)" />
                <div class="evid-firstKey">{{ treeDoc.treeName }}</div>
              </div>
              <div class="evid-secondBox">
                <div
                  v-for="(document) in treeDoc.treeDocList"
                  :key="document.id"
                  class="evid-second"
                  :class="{ active: document.id === currentDocId }"
                  @click="
                    clickDocName(document.id, treeDoc, document)
                  "
                >
                  <div class="evid-secondKey" :title="document.docName">
                    <div
                      v-show="!document.error"
                      class="tree-check-icon"
                      :class="{'active' : document.checked}"
                      @click.stop="handleNameCheck(treeDoc, document)"
                    />
                    {{ document.docName }}
                  </div>
                  <span v-if="imageMaps[document.id] && imageMaps[document.id].length" class="complete el-icon-circle-check" />
                </div>
              </div>
            </div>
          </template>
          <!-- <div v-if="evidenceList && evidenceList.length > 0 && tabValue === 'evidence'">
            <div
              v-for="(evidence, index) in evidenceList"
              :key="evidence.id"
              class="evid-con"
            >
              <div class="evid-first">
                <div class="evid-firstKey">
                  <div
                    v-if="totalDocNum(evidence.evidList)"
                    class="tree-check-icon"
                    :class="{'active' : evidence.checked}"
                    @click.stop="handleEvidFirstNameCheck(index)"
                  />
                  {{ evidence.personName }}</div>
                <div class="evid-firstNum">
                  ({{ totalDocNum(evidence.evidList) }})
                </div>
              </div>
              <div class="evid-secondBox">
                <div v-for="(evid) in evidence.evidList" :key="evid.id">
                  <div class="evid-second">
                    <div class="evid-secondKey" :title="evid.evidName">
                      <div
                        v-if="evid.docList.length"
                        class="tree-check-icon"
                        :class="{'active' : evid.checked}"
                        @click.stop="handleEvidSecondNameCheck(evidence, evid)"
                      />
                      {{ evid.evidName }}
                    </div>
                    <div class="evid-secondNum">{{ evid.docList.length }}</div>
                  </div>
                  <div class="evid-thirdBox">
                    <div
                      v-for="(document) in evid.docList"
                      :key="document.id"
                      :title="document.docName"
                      class="evid-third"
                      :class="{ active: document.id === currentDocId }"
                      @click="
                        clickEvidName( document.id, document.docType )
                      "
                    >
                      <div
                        v-show="!document.error && !['mp3', 'mp4', 'zip'].includes(document.docType)"
                        class="tree-check-icon"
                        :class="{'active' : document.checked}"
                        @click.stop="handleEvidThirdNameCheck(evidence, evid, document)"
                      />
                      {{ document.docName }}
                      <span v-if="imageMaps[document.id] && imageMaps[document.id].length" class="complete el-icon-circle-check" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div> -->
        </div>
      </div>
    </div>
    <div class="noTouch-signBox">
      <div ref="noTouchSignCon" class="noTouch-signCon">
        <div id="pdf_view_wrapper" style="position: relative">
          <div v-if="canvasShow" style="position: absolute">
            <div
              v-for="key of dragList"
              :id="'drag_container'+key"
              :key="key"
              style="position: relative;overflow: hidden"
              :style="dragPositions[key] || dragPosition"
            >
              <VueDragResize
                v-for="(item, index) in imageMaps[key]"
                v-show="!item.isDeleted"
                :key="item.id || index"
                :x="item.left"
                :y="item.top"
                :w="item.width"
                :h="30"
                :parent-w="divWidth"
                :parent-h="parseInt(dragPositions[key].height)"
                axis="both"
                :parent-limitation="true"
                :is-active="true"
                :is-draggable="true"
                :is-resizable="false"
                @dragstop="dragEnd($event, index, key)"
              >
                <div>
                  <p class="deletedImgClass" @click="deletedSign(key, index)">×</p>
                </div>
                <template v-if="item.isCompany">
                  <div class="noTouch-signName company-img" />
                  <div class="noTouch-signKey">公章</div>
                </template>
                <template v-else>
                  <div class="noTouch-setSign">
                    <span v-for="(word, wi) in item.cnName" :key="wi">{{ word }}</span>
                  </div>
                  <div class="noTouch-signKey">
                    {{ item.roleName }}
                  </div>
                </template>
              </VueDragResize>
            </div>
          </div>

          <!-- 文书列表 -->
          <div v-for="key of docList" v-show="tabValue === 'file'" :key="key" class="files-canvas">
            <canvas
              v-for="page of docNumPages[key]"
              :id="`pdf_view${key}_${page}`"
              :key="`${key}-${page}`"
              :ref="`pdf_viewer${key}_${page}`"
              :attrId="key"
            />
          </div>
          <!-- 证据材料 -->
          <div v-for="key of evidenceArr" v-show="tabValue === 'evidence'" :key="key" class="evidences-canvas">
            <canvas
              v-for="page of docNumPages[key]"
              :id="`pdf_view${key}_${page}`"
              :key="`${key}-${page}`"
              :ref="`pdf_viewer${key}_${page}`"
              :attrId="key"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="noTouch-signCont">
      <div class="no-touch-btn">
        <!-- <el-button type="primary" class="close-btn" @click="oneAdd">一键添加</el-button> -->
        <el-button type="primary" class="close-btn" @click="oneDelete">一键删除</el-button>
        <el-button type="primary" class="close-btn" @click="closeShowBack">完成</el-button>
      </div>
      <div class="noTouch-signTop">
        <div class="receive-costTitle noTouch-signL">当事人</div>
        <div class="noTouch-signS">拖动姓名框可设置签署位</div>
        <el-button class="tool-btn" style="height:32px" @click="oneAdd">一键添加</el-button>
      </div>
      <div
        v-for="person in personData"
        :key="person.id + person.subject"
        class="noTouch-signPerson"
        style="z-index: 1"
        @mousedown="handleDown(person, $event)"
      >
        <div style="position:relative;">
          <el-popover
            v-model="signVisible[person.id]"
            placement="top-start"
            width="200"
            trigger="manual"
            content="是事项关联的当事人"
            popper-class="popover-container-black"
          >
            <div v-if="person.notaryItemId" slot="reference" class="noTouch-signStar" @click="handlePopover(person.id)" />
          </el-popover>
        </div>
        <div class="noTouch-signName"><!-- {{ person.cnName }} -->
          <span v-for="(word, wi) in person.cnName" :key="wi">{{ word }}</span>
        </div>
        <div class="noTouch-signKey">
          {{ person.resName }}
        </div>
      </div>
      <div
        v-for="person in companyData"
        :key="person.id + person.subject"
        class="noTouch-signCompany"
        style="z-index: 1"
      >
        <div
          v-if="person.customerType === 2 && showPerson(person)"
          class="noTouch-sign-wrap"
        >
          <div class="company-name-title">{{ person.cnName }}</div>
          <div
            class="noTouch-sign-item"
            @mousedown="handleDown(person, $event)"
          >
            <div style="position:relative;">
              <el-popover
                v-model="signVisible[person.id]"
                placement="top-start"
                width="200"
                trigger="manual"
                content="是事项关联的当事人"
                popper-class="popover-container-black"
              >
                <div v-if="person.notaryItemId" slot="reference" class="noTouch-signStar" @click="handlePopover(person.id)" />
              </el-popover>
            </div>
            <div class="company-img" />
            <div class="noTouch-signKey">公章</div>
          </div>
          <div
            v-for="item of person.children"
            :key="item.id"
            class="noTouch-sign-item"
            @mousedown="handleDown(item, $event)"
          >
            <div class="noTouch-signName"><!-- {{ item.cnName }} -->
              <span v-for="(word, wi) in item.cnName" :key="wi">{{ word }}</span>
            </div>
            <div class="noTouch-signKey">
              {{ item.resName }}
            </div>
          </div>
        </div>
      </div>
      <div v-if="notaryOnlineSign">
        <div class="noTouch-signTop" style="margin-top: 20px">
          <div class="receive-costTitle noTouch-signL">公证人员</div>
          <div class="noTouch-signS">拖动姓名框可设置签署位</div>
        </div>
        <div
          v-for="person in notaryPersonList"
          :key="person.id"
          class="noTouch-signPerson"
          style="z-index: 1"
          @mousedown="handleDown(person, $event)"
        >
          <div class="noTouch-signName">
            <!-- {{ person.cnName }} -->
            <span v-for="(word, wi) in person.cnName" :key="wi">{{ word }}</span>
          </div>
          <div class="noTouch-signKey">
            {{ person.resName }}
          </div>
        </div>
      </div>
    </div>
    <div
      class="drag-temp-wrap noTouch-signPerson"
      style="position: absolute; z-index: 0"
      :style="dragTemp.position"
    >
      <template v-if="dragTemp.person.isCompany">
        <div class="noTouch-signName company-img nobd" />
        <div class="noTouch-signKey">
          {{ dragTemp.person.resName }}
        </div>
      </template>
      <template v-else>
        <div class="noTouch-signName"><!-- {{ dragTemp.person.cnName }} -->
          <span v-for="(word, wi) in dragTemp.person.cnName" :key="wi">{{ word }}</span>
        </div>
        <div class="noTouch-signKey">
          {{ dragTemp.person.resName }}
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import Pdfjs from 'pdfjs-dist'
import VueDragResize from 'vue-drag-resize'
import { getZTConfigDetail } from '../../../api/bzxt/common/NotaryOffice'
// import { AnnotationFlag } from '../../../../static/pdf/build/pdf.worker'
export default {
  name: 'NoTouchSign',
  components: {
    VueDragResize
  },
  props: {
    notaryFileVo: {
      type: Object,
      default: () => {
        return {}
      }
    },
    currentDoc: {
      type: Object,
      default: () => {
        return {}
      }
    },
    closeShowBack: {
      type: Function,
      default: () => {}
    },
    height: {
      type: String,
      default: '842px'
    }
  },
  data () {
    return {
      canInsert: false,
      loadPdf: false,
      doc: null,
      // numPages: 1,
      currentPage: 1,
      dowmPdfFile: '/api/file/fileService/downloadFile',
      dragPosition: {
        width: 800,
        height: 841,
        left: 500
      },
      // imageMap: [],
      divWidth: 0,
      divHeight: 0,
      signatureConfigList: [],
      notarySignInfo: {},
      websock: null,
      projectHost: '',
      evidenceList: [],
      documentTree: [],
      personList: [],
      currentDocId: undefined,
      currentDocType: -1,
      dragTemp: {
        person: {},
        position: {
          width: 800,
          height: 841,
          left: 500,
          display: 'none'
        }
      },
      loadPersonType: 0, // 0加载卷宗当事人， 1 加载事项当事人 ，2 加载材料当事人
      loadItemId: '',
      loadNotaryPersonId: '',
      tabValue: 'file',
      imageMaps: {},
      docNumPages: {},
      evidenceNumPages: {},
      docList: [],
      dragPositions: {},
      docInfos: {}, // 文书map
      evidenceArr: [],
      evidenceInfos: {},
      notaryPersonList: [],
      notaryOnlineSign: false, // 是否开启线上签署
      signVisible: {},
      currentItem: {},
      currentDocTemp: {},
      firstJoin: true,
      canvasShow: true
    }
  },
  computed: {
    // 筛掉了代理人，现在加回来解决bug66516
    personData () {
      const data = []
      this.personList.forEach((person) => {
        if (!(person.customerType === 2)) {
          data.push(person)
        }
        // if (
        //   person.customerType === 1 &&
        //   person.resName !== '代理人' &&
        //   this.showPerson(person)
        // ) {
        //   data.push(person)
        // }
      })
      return data
    },
    companyData () {
      const temp = {}
      const companyObj = {}
      this.personList.forEach((person) => {
        if (
          person.customerType === 2 &&
          this.showPerson(person)
        ) {
          if (person.isCompany) {
            companyObj[person.id] = person.companyCnName
            temp[person.companyCnName] = { ...person, children: [] }
          } else if (temp[person.companyCnName]) {
            temp[person.companyCnName].children.push(person)
          }
        }
      })
      const other = this.personList.filter(
        (person) => person.resName === '代理人'
      )
      if (other && other.length > 0) {
        other.forEach((person) => {
          const p = companyObj[person.unitId]
          if (p) {
            temp[p].children.push(person)
          }
        })
      }
      // console.log(temp)
      const data = Object.values(temp)
      return data
    },
    dragList () {
      return this.tabValue === 'file' ? this.docList : this.evidenceArr
    }
  },
  created () {
    this.getPersonByFile()
    this.getNotaryDocumentByFile()
    this.loadAllEvidenceList()
    this.getgenNotaryPerson()
    this.getZTConfigDetail()
    Pdfjs.GlobalWorkerOptions.workerSrc = 'pdfjs-dist/build/pdf.worker.js'
  },
  mounted () {
    this.$nextTick(() => {
      if (document.querySelector('.noTouch-signCon')) {
        document.querySelector('.noTouch-signCon')
          .addEventListener('mousewheel', this.handleMousewheel)
      }
    })
  },
  methods: {
    getZTConfigDetail () {
      getZTConfigDetail().then(res => {
        this.notaryOnlineSign = res.data.notaryOnlineSign
      })
    },
    getgenNotaryPerson () {
      const data = { notaryFileId: this.notaryFileVo.id }
      genNotaryPerson(data).then(res => {
        this.notaryPersonList = res.data || []
      })
    },
    showPerson (person, ...args) {
      /* let { loadPersonType, loadItemId, loadNotaryPersonId } = this.$data
      if (args.length) {
        [loadPersonType, loadItemId, loadNotaryPersonId] = args
      }
      if (loadPersonType === 0) {
        return true
      }
      if (loadPersonType === 2) {
        return loadNotaryPersonId === person.id
      }
      let isExitItemPerson = false
      for (let i = 0; i < this.personList.length; i++) {
        if (
          this.personList[i].notaryItemId &&
          this.personList[i].notaryItemId.indexOf(loadItemId) > -1
        ) {
          isExitItemPerson = true
          break
        }
      }
      if (!isExitItemPerson) {
        return true
      } else {
        return person.notaryItemId && person.notaryItemId.indexOf(loadItemId) > -1
      } */
      return true
    },
    /**
     * 计算文档数量
     */
    totalDocNum (evidList) {
      let i = 0
      for (const evid of evidList) {
        i += evid.docList.length
      }
      return i
    },
    oneAdd () {
      let infos = this.docInfos
      const numPages = this.docNumPages
      if (this.tabValue === 'evidence') {
        infos = this.evidenceInfos
      }
      const values = Object.values(infos)
      const hasChecked = values.some(item => item.checked)
      if (!hasChecked) {
        this.$message.error('请勾选要签署的文书！')
        return
      }

      const personData = []
      this.personData.forEach(val => {
        personData.unshift(val)
      })
      const companyData = []
      this.companyData.forEach(val => {
        companyData.unshift(val)
        if (val.children) {
          val.children.forEach(item => {
            companyData.unshift(item)
          })
        }
      })
      const notaryPersonList = []
      this.notaryPersonList.forEach(val => {
        notaryPersonList.unshift(val)
      })
      const signFunc = ({ page, item, signX, signY, key, doc }) => {
        return {
          keyword: page,
          signPage: page,
          right: signX,
          down: signY + ((page - 1) * 841),
          left: signX,
          top: signY + ((page - 1) * 841),
          cnName: item.cnName,
          subject: item.subject,
          agentType: item.agentType,
          custType: item.custType,
          roleName: item.resName,
          resName: item.resName,
          notaryFileId: item.notaryFileId,
          personId: item.id,
          personName: item.cnName,
          width: 100,
          height: item.isCompany ? 100 : 30,
          isDeleted: false,
          fileId: key,
          docType: this.tabValue === 'file' ? doc.docType : -1,
          isCompany: item.isCompany,
          signX,
          signY: signY + ((page - 1) * 841),
          notarySign: item.notarySign
        }
      }

      // 从后往前盖章， 区分是否可以盖公章
      const params = []
      for (const [key, doc] of Object.entries(infos)) {
        if (!doc.checked) {
          continue
        }
        let signY = 700
        let signX = 460
        const signList = []
        const pages = numPages[key]

        // 公章
        companyData.forEach(item => {
          const { isCommonDoc, treeId } = doc
          let loadPersonType = 1
          let loadItemId = treeId
          const loadNotaryPersonId = '' // 材料时有值
          if (isCommonDoc) {
            loadPersonType = 0
            loadItemId = ''
          }
          if (item.customerType === 2 && this.showPerson(item, loadPersonType, loadItemId, loadNotaryPersonId)) {
            // 每一个同一位置盖章
            for (let page = 1; page <= pages; page++) {
              const temp = signFunc({ page, item, signX, signY, key, doc })
              signList.push(temp)
            }
            signX -= 110
            if (signX < 0) {
              signX = 460
              signY -= 110
            }
          }
        })

        // 个人章
        personData.forEach(item => {
          // 每一个同一位置盖章
          for (let page = 1; page <= pages; page++) {
            const temp = signFunc({ page, item, signX, signY, key, doc })
            signList.push(temp)
          }
          signX -= 110
          if (signX < 0) {
            signX = 460
            signY -= 110
          }
        })
        // if (this.notaryOnlineSign) {
        //   // 公证人章
        //   notaryPersonList.forEach(item => {
        //     // 每一个同一位置盖章
        //     for (let page = 1; page <= pages; page++) {
        //       const temp = signFunc({ page, item, signX, signY, key, doc })
        //       signList.push(temp)
        //     }
        //     signX -= 110
        //     if (signX < 0) {
        //       signX = 460
        //       signY -= 110
        //     }
        //   })
        // }
        params.push({ documentId: key, signList })
      }
      this.saveOnceAddSigns(params)
    },
    saveOnceAddSigns (params) {
      const loading = this.$loading({
        lock: true,
        text: '添加中...',
        spinner: 'el-icon-loading',
        background: 'transparent',
        target: this.$el
      })
      this.loadPdf = true
      const param = []
      params.map(item => param.push(...item.signList))
      saveNotarySmallDocSigns(param).then(res => {
        if (res.code === 0) {
          params.forEach((item, index) => {
            // this.imageMaps[item.documentId].push(...item.signList)
            const { notaryFileId, fileId } = item.signList[0] || {}
            if (index === params.length - 1) {
              this.loadSign(notaryFileId, fileId, 1, loading)
            } else {
              this.loadSign(notaryFileId, fileId, 1)
            }
          })
        } else {
          this.$message.error(res.message)
          loading.close()
        }
        this.loadPdf = false
      })
        .catch(() => {
          loading.close()
          this.loadPdf = false
        })
    },
    async oneDelete () {
      let infos = this.docInfos
      if (this.tabValue === 'evidence') {
        infos = this.evidenceInfos
      }
      const values = Object.values(infos)
      const hasChecked = values.some(item => item.checked)
      if (!hasChecked) {
        this.$message.error('请勾选要签署的文书！')
        return
      }

      const loading = this.$loading({
        lock: true,
        text: '删除中...',
        spinner: 'el-icon-loading',
        background: 'transparent',
        target: this.$el
      })
      const promiseAll = []
      await values.forEach(async item => {
        if (item.checked) {
          const imageMap = this.imageMaps[item.id]
          for (let i = 0; i < imageMap.length; i++) {
            // await deleteSign(imageMap[i].id || imageMap[i].fileId)
            const temp = new Promise(resolve => {
              resolve(deleteSign(imageMap[i].id || imageMap[i].fileId))
            })
            promiseAll.push(temp)
          }
          this.imageMaps[item.id] = []
        }
      })
      Promise.all(promiseAll).then(res => {
        loading.close()
      })
    },
    handleDown (person, event) {
      console.log(person, event)
      if (!this.currentDocId) {
        let id = ''
        if (this.tabValue === 'file') {
          id = document.querySelector('.files-canvas canvas').getAttribute('attrId')
        } else if (this.tabValue === 'evidence') {
          id = document.querySelector('.evidences-canvas canvas').getAttribute('attrId')
        }
        this.currentDocId = id
      }
      if (!this.canInsert || !this.currentDocId) {
        this.$message.error('请先打开需要添加签章的文件')
        return
      }
      // const sidebarWidth = document.querySelector('.hideSidebar') ? 55 : document.querySelector('.openSidebar') ? 205 : 0
      const scrollTop = document.querySelector('.noTouch-signCont').scrollTop
      const elmTop = event.target.offsetTop - 20 - scrollTop
      const elmLeft = event.target.offsetLeft
      let signTop = 160
      const el = document.querySelector('.noTouch-signCon')
      let node = el.parentNode
      let noDialog = true
      while (node && noDialog) {
        if (node.className && node.className.indexOf('el-dialog__body') > -1) {
          noDialog = false
        } else {
          node = node.parentNode
        }
      }
      if (!noDialog) {
        const rect = el.getBoundingClientRect()
        signTop = rect.top
      }
      this.dragTemp.person = person
      this.dragTemp.position.top = elmTop + 'px'
      this.dragTemp.position.left = elmLeft + 'px'
      this.dragTemp.position.width = (event.target.offsetWidth < 100 ? 100 : event.target.offsetWidth) + 'px'
      this.dragTemp.position.height = event.target.offsetHeight + 'px'
      this.dragTemp.position.display = 'block'
      const { clientX, clientY } = event
      document.onmousemove = (e) => {
        this.dragTemp.position.top = e.clientY - clientY + elmTop + 'px'
        this.dragTemp.position.left = e.clientX - clientX + elmLeft + 'px'
        console.log(this.dragTemp.position.top)
      }
      document.onmouseup = () => {
        this.dragTemp.position.display = 'none'
        document.onmousemove = null
        document.onmouseup = null
        const scrollTop1 = el.scrollTop
        const left = parseFloat(this.dragTemp.position.left)
        let top = parseFloat(this.dragTemp.position.top) + scrollTop1
        const evidWidth = document.querySelector('.evid-l').offsetWidth
        const contentWidth = el.offsetWidth
        let ml =
          (document.querySelector('.noTouch-signBox').offsetWidth -
            contentWidth) /
          2
        if (ml < 0) {
          ml = 0
        }
        // 跨页调整top
        let height = 0
        let paddingTop = noDialog ? 170 : signTop
        const canvasParent = this.tabValue === 'file' ? '.files-canvas' : '.evidences-canvas'
        const canvasElms = Array.from(
          document
            .querySelector('#pdf_view_wrapper')
            .querySelector(canvasParent)
            .querySelectorAll('canvas') || []
        )
        console.log(signTop)
        const flag = canvasElms.some((elm) => {
          paddingTop += 20
          height += elm.offsetHeight
          return height > top && height < top + signTop
        })
        console.log(flag)
        // if (flag) {
        //   top = height - signTop
        // } else {
        //   paddingTop = 20
        // }
        if (noDialog) {
          paddingTop = 170
        }
        // end
        // 判断当前位置处于哪一份文书
        let temp = 0
        let key = ''
        const list = this.tabValue === 'file' ? this.docList : this.evidenceArr
        list.some(item => {
          const dh = (this.dragPositions[item] && parseFloat(this.dragPositions[item].height)) || 0
          if (temp + dh > top) {
            key = item
            return true
          }
          temp += dh
          return false
        })
        top -= temp
        const divHeight = parseFloat(this.dragPositions[key].height)
        const numPages = this.docNumPages[key]
        this.currentDocId = key
        this.currentPage = Math.ceil(top / (divHeight / numPages))
        const { isCommonDoc, treeId, docType } = this.docInfos[key] || {}
        if (isCommonDoc) {
          this.loadPersonType = 0
        } else {
          this.loadItemId = treeId
          this.loadPersonType = 1
        }
        if (docType === 'mp3' || docType === 'mp4' || docType === 'zip') {
          this.$message.warning(docType + '不支持签署')
          return
        }
        this.currentDocType = this.tabValue === 'evidence' ? -1 : docType
        this.canInsert = true
        // end
        const w1 = evidWidth + ml
        const w2 = w1 + contentWidth
        if (left > w1 && left < w2) {
          // 设置一个添加到页末的偏移
          const offset = top + 30 > divHeight
          console.log(top, divHeight, numPages, paddingTop - signTop, offset)
          const sign = {
            keyword: Math.ceil(top / (divHeight / numPages)),
            signPage: Math.ceil(top / (divHeight / numPages)),
            signY: (top < 0 ? 0 : top) + paddingTop - signTop - (offset ? 30 : 0), // 判断是页末加偏移,页头偏移为0
            signX: left - evidWidth - ml
          }
          this.firstAddSave(person, sign)
        }
      }
    },
    firstAddSave (person, sign) {
      const loading = this.$loading({
        lock: true,
        text: '添加中...',
        spinner: 'el-icon-loading',
        background: 'transparent',
        target: this.$el
      })
      this.loadPdf = true
      sign = {
        keyword: this.currentPage,
        signPage: this.currentPage,
        right: sign.signX,
        down: sign.signY,
        left: sign.signX,
        top: sign.signY,
        cnName: person.cnName,
        subject: person.subject,
        agentType: person.agentType,
        custType: person.custType,
        roleName: person.resName,
        resName: person.resName,
        notaryFileId: person.notaryFileId,
        personId: person.id,
        personName: person.cnName,
        width: 100,
        height: person.isCompany ? 100 : 30,
        isDeleted: false,
        fileId: this.currentDocId,
        docType: this.currentDocType,
        isCompany: person.isCompany,
        notarySign: person.notarySign,
        ...sign
      }
      saveNotarySmallDocSign(sign)
        .then((res) => {
          if (res.code === 0) {
            sign.id = res.data
            this.imageMaps[this.currentDocId].push(sign)
          } else {
            this.$message.error(res.message)
          }
          loading.close()
          this.loadPdf = false
        })
        .catch(() => {
          loading.close()
          this.loadPdf = false
        })
    },
    /**
     * 删除签章
     */
    deletedSign (key, index) {
      const loading = this.$loading({
        lock: true,
        text: '删除中...',
        spinner: 'el-icon-loading',
        background: 'transparent',
        target: this.$el
      })
      deleteSign(this.imageMaps[key][index].id).then((res) => {
        if (res.code === 0) {
          // this.renderPage(this.currentPage, this.currentDocId)
          this.imageMaps[key].splice(index, 1)
          // this.$set(this.imageMaps, key, this.imageMaps[key])
          this.$forceUpdate()
        } else {
          this.$message.error(res.message)
        }
        loading.close()
      })
    },
    /* 拖拽结束 - 调整跨页 */
    dragEnd (newRect, index, key) {
      this.imageMaps[key][index].signX = newRect.left
      this.imageMaps[key][index].signY = newRect.top
      this.imageMaps[key][index].top = newRect.top

      const numPages = this.docNumPages[key]
      const top = this.imageMaps[key][index].signY
      const height = parseInt(this.dragPositions[key].height) / numPages
      // const height = parseInt(this.imageMaps[key][index].height) / numPages
      this.imageMaps[key][index].signPage = Math.ceil(newRect.top / height)
      const offsety = 30
      for (let i = 1; i < numPages; i++) {
        const h = height * i
        if (h > top && h < top + offsety) {
          const temp = {
            ...this.imageMaps[key][index],
            signY: h - offsety,
            top: h - offsety,
            signPage: i
          }
          this.imageMaps[key][index] = temp
          newRect.top = h - offsety
          document.querySelector('#drag_container').querySelectorAll('.vdr')[ index ].style.top = h - offsety + 'px'
          break
        }
      }
      saveNotarySmallDocSign(this.imageMaps[key][index]).then((res) => {
        if (res.code !== 0) {
          this.$message.error(res.message)
        }
      })
    },
    /**
     * 加载文件的签章
     */
    loadSign (notaryFileId, fileId, page, loading) {
      findNotarySmallDocSign({ notaryFileId, fileId, page }).then((res) => {
        if (res.code === 0) {
          const imageMap = []
          for (const docSign of res.data) {
            let signY = docSign.signY
            const h = parseFloat(this.dragPositions[fileId].height) / this.docNumPages[fileId]
            const preHeight = h * (docSign.signPage - 1)
            if (signY < preHeight) {
              signY += preHeight
            }
            const sign = {
              width: 100,
              height: docSign.isCompany ? 100 : 30,
              isDeleted: false,
              keyword: docSign.signPage,
              signPage: docSign.signPage,
              right: docSign.signX,
              down: signY,
              left: docSign.signX,
              top: signY,
              signX: docSign.signX,
              signY: signY,
              cnName: docSign.personName,
              roleName: docSign.roleName,
              notaryFileId: docSign.notaryFileId,
              personId: docSign.personId,
              fileId: docSign.fileId,
              id: docSign.id,
              isCompany: docSign.unitName === docSign.personName
            }
            imageMap.push(sign)
          }
          this.$set(this.imageMaps, fileId, imageMap)
        } else {
          this.$message.error(res.message)
        }
        if (loading) {
          loading.close()
        }
        this.loadPdf = false
      })
    },
    /**
     * 单击材料名
     */
    clickEvidName (id, docType) {
      const evid = this.evidenceInfos[id] || {}
      if (['mp3', 'mp4', 'zip'].includes(docType)) {
        let mes = docType
        if (['mp3', 'mp4'].includes(docType)) {
          mes = '音视频文件'
        }
        this.$message.warning(mes + '不支持签署')
        return
      }
      if (evid.error) {
        this.$message.error(evid.docName + '生成出错，请联系管理员!')
        return
      }
      const to = (document.getElementById('drag_container' + id) || {}).offsetTop
      const elt = this.$refs.noTouchSignCon
      this.$utils.scrollTo(to, 500, elt)
      this.setCurEvidenceStatus(id)
    },
    checkDocumentBox (parent, row) {
      // 先所有的勾选删除掉
      for (let i = 0; i < this.documentTree.length; i++) {
        const docTree = this.documentTree[i]
        docTree.checked = false
        const treeDocList = docTree.treeDocList || []
        for (let j = 0; j < treeDocList.length; j++) {
          treeDocList[j].checked = false
        }
      }
      // 选中当前行
      row.checked = true
      parent.checked = parent.treeDocList.every(item => item.checked)
    },
    /**
     * 单击文件名
     */
    clickDocName (id, parent, row) {
      if (!this.firstJoin && this.currentDocTemp.id === id) return
      const doc = this.docInfos[id] || {}
      if (doc.error) {
        this.$message.error(doc.docName + '生成出错，请联系管理员!')
        return
      }
      this.currentItem = parent
      this.currentDocTemp = row
      this.checkDocumentBox(parent, row)
      // const to = (document.getElementById('drag_container' + id) || {}).offsetTop
      // const elt = this.$refs.noTouchSignCon
      // this.$utils.scrollTo(to, 500, elt)
      this.setCurStatus(id)
      if (this.firstJoin) {
        this.firstJoin = false
        return
      }
      this.loadAllDoc(this.documentTree, true)
    },
    /**
     * 转换PDF
     */
    transPdf ({ loading, id, index, firstIndex }) {
      this.canInsert = true
      loading.text = '转换文档中...'
      transFileToPdf({ documentId: id, docType: 2 })
        .then((res) => {
          if (res.code === 0 && res.data !== null) {
            this.initPdfComponent(res.data, id, loading)
            this.documentTree[firstIndex].treeDocList[index].pdfFileId = res.data
            this.canvasShow = true
          } else {
            this.loadPdf = false
            loading.close()
            this.$message.error(res.message)
            this.documentTree[firstIndex].treeDocList[index].error = true
          }
          if (this.firstJoin) {
            this.clickDocName(this.currentDocTemp.id, this.currentItem, this.currentDocTemp)
          }
        })
        .catch((e) => {
          this.loadPdf = false
          this.documentTree[firstIndex].treeDocList[index].error = true
          loading.close()
        })
    },
    /**
     * 加载pdf文件
     */
    initPdfComponent (pdfFileId, fileId, loading) {
      // this.imageMap = []
      loading.text = '拼命加载中...'
      this.pdfFileViewUrl = this.dowmPdfFile + '?fileId=' + pdfFileId + '&_t=' + Math.random()
      const loadingTask = Pdfjs.getDocument({ url: this.pdfFileViewUrl })
      loadingTask.promise
        .then((pdf) => {
          this.doc = pdf
          // this.numPages = pdf.numPages
          // this.docNumPages[fileId] = pdf.numPages
          this.$set(this.docNumPages, fileId, pdf.numPages)
          this.currentPage = 1
          // document.querySelector('.noTouch-signCon').scrollTop = 0
          this.$nextTick(() => {
            for (let i = 1; i <= this.docNumPages[fileId]; i++) {
              this.renderPage(i, fileId, loading)
            }
          })
        })
        .catch(() => {
          this.loadPdf = false
          if (this.tabValue === 'file') {
            this.docInfos[fileId].error = true
          } else {
            this.evidenceInfos[fileId].error = true
          }
          loading.close()
        })
    },
    /**
     * 页码切换
     */
    renderPage (currentPage, fileId, loading) {
      if (!loading) {
        if (!fileId) {
          this.$message.error('请先打开需要添加签章的文件')
          return
        }
        loading = this.$loading({
          lock: true,
          text: '拼命加载中...',
          spinner: 'el-icon-loading',
          background: 'transparent',
          target: this.$el
        })
      }
      this.doc.getPage(currentPage).then((page) => {
        const defViewport = page.getViewport({ scale: 1 })
        const width = this.$refs.noTouchSignCon.offsetWidth || 800
        const scale = (width / defViewport.width).toFixed(2)
        const viewport = page.getViewport({ scale }) || {}
        // const viewport = page.getViewport({ scale: scale })
        const canvas = document.getElementById(`pdf_view${fileId}_${currentPage}`)
        const context = canvas.getContext('2d')
        canvas.height = viewport.height
        canvas.width = viewport.width
        const pdf_viewerRef = this.$refs[`pdf_viewer${fileId}_${currentPage}`][0]
        this.divWidth = pdf_viewerRef.width
        let { height } = this.dragPositions[fileId] || {}
        if (currentPage === 1) {
          height = pdf_viewerRef.height + 'px'
          // this.divHeight = pdf_viewerRef.height
        } else {
          height = parseFloat(height) + pdf_viewerRef.height + 'px'
          // this.divHeight += pdf_viewerRef.height
        }
        this.$set(this.dragPositions, fileId, { width: pdf_viewerRef.width + 'px', height, left: pdf_viewerRef.offsetLeft + 'px' })
        const renderContext = {
          canvasContext: context,
          viewport: viewport
        }
        page.render(renderContext)
        if (fileId) {
          this.loadSign(this.notaryFileVo.id, fileId, this.currentPage, loading)
        } else {
          if (loading && this.docNumPages[fileId] === currentPage) {
            loading.close()
          }
          this.loadPdf = false
        }
      })
    },
    /**
     * 加载证据材料
     */
    loadAllEvidenceList () {
      getAllEvidenceList({
        notaryFileId: this.notaryFileVo.id,
        loadData: false
      }).then((res) => {
        this.evidenceList = res.data
      })
    },
    /**
     * 加载文书
     */
    getNotaryDocumentByFile () {
      findNotaryDocumentByFile({ notaryFileId: this.notaryFileVo.id }).then(
        (res) => {
          if (res.data !== null && res.data.length > 0) {
            this.documentTree = res.data
          }
          /* // 默认加载第一份文书
          if (
            this.documentTree &&
            this.documentTree.length > 0 &&
            this.documentTree[0] &&
            this.documentTree[0].treeDocList &&
            this.documentTree[0].treeDocList.length > 0
          ) {
            const { fileId, pdfFileId, id, docType, notaryItemId } = this.documentTree[0].treeDocList[0]
            this.clickDocName(fileId, pdfFileId, id, 0, docType, 0, false, notaryItemId)
          } */
          // 2021.11.16 加载全部文件
          const empty = this.documentTree.some(item => {
            return item.treeDocList && item.treeDocList.length
          })
          if (!empty) {
            return
          }
          this.loadAllDoc(this.documentTree)
          // this.documentTree.forEach(item => {
          //   if (item.treeDocList && item.treeDocList.length) {
          //     if (item.treeDocList.map(ite => ite.id).includes(this.currentDoc.id)) {
          //       this.currentItem = item
          //       this.currentDocTemp = item.treeDocList.filter(ite => ite.id === this.currentDoc.id)[0]
          //     }
          //   }
          // })
        }
      )
    },
    /**
     * 加载当事人
     */
    getPersonByFile () {
      findNotaryFileItemPersonRes({ notaryFileId: this.notaryFileVo.id }).then(
        (res) => {
          // 过滤当事人
          const personList = []
          if (res.code === 0) {
            const list = res.data
            for (let i = 0; i < list.length; i++) {
              if (
                list[i].customerType === 1 &&
                list[i].cnName &&
                list[i].certificateNo
              ) {
                const person = {
                  ...list[i],
                  subject: false,
                  custType: false,
                  agentType: false
                }
                personList.push(person)
              } else if (list[i].customerType === 2) {
                if (list[i].companyCnName && list[i].certificateNo) {
                  const person = JSON.parse(JSON.stringify(list[i]))
                  person.cnName = person.companyCnName
                  person.contactNumber = person.corporationContactNumber
                  person.subject = true
                  person.custType = true
                  person.agentType = false
                  // 企业-公章
                  person.isCompany = true
                  personList.push(person)
                }
                if (
                  list[i].legalPersonName &&
                  list[i].corporationCertificateNo
                ) {
                  const person = JSON.parse(JSON.stringify(list[i]))
                  person.cnName = person.legalPersonName
                  person.certificateNo = person.corporationCertificateNo
                  person.contactNumber = person.corporationContactNumber
                  person.resName = '法定代表人'
                  person.subject = false
                  person.custType = true
                  person.agentType = false
                  personList.push(person)
                }
              }
            }
          }
          this.personList = personList
        }
      )
    },
    onFilePageChange (event, type) {
      const curPage = this.currentPage + type
      const elt = document.querySelector('.noTouch-signCon') // ('.noTouch-signBox')
      if (type === 'top' || curPage === 1) {
        this.currentPage = 1
        elt.scrollTop = 0
      } else if (type === 'bottom') {
        this.currentPage = this.numPages
        elt.scrollTop = elt.scrollHeight
      } else {
        if (curPage === 0 || curPage === this.numPages + 1) {
          return
        }
        this.currentPage = curPage
      }
      const top = (elt.scrollHeight / this.numPages) * (this.currentPage - 1)
      elt.scrollTop = top
      return false
    },
    handleMousewheel (e) {
      e = e || window.event
      let delta = e.wheelDelta ? e.wheelDelta : -e.detail
      delta = delta > 0 ? 0 : 1
      const elm = document.querySelector('.noTouch-signCon')
      const top = elm.scrollTop
      const h = 841 // document.querySelector('#pdf_view1').offsetHeight
      let curPage = Math.ceil(top / h) || 1
      top % h > h / 2 ? (curPage += delta) : null
      let total = 0
      let id = ''
      const list = this.tabValue === 'file' ? this.docList : this.evidenceArr
      list.some(key => {
        const pages = this.docNumPages[key] || 0
        id = key
        total += pages
        return curPage <= total
      })
      if (this.tabValue === 'file') {
        this.setCurStatus(id)
      } else {
        this.setCurEvidenceStatus(id)
      }
      this.currentPage = total - curPage
    },
    loadAllDoc (data) {
      if (data.length > 0) {
        const loading = this.$loading({
          lock: true,
          text: '拼命加载中...',
          spinner: 'el-icon-loading',
          background: 'transparent',
          target: this.$el
        })
        this.loadPdf = true
        this.canvasShow = false
        this.docInfos = {}
        this.docList = []
        const tempList = []
        if (!this.currentDoc.id && this.firstJoin) {
          data.forEach((item) => {
            const treeDocList = item.treeDocList || []
            treeDocList.forEach(async (doc) => {
              tempList.push(doc)
            })
          })
          if (tempList.length > 0) {
            this.currentDocTemp = tempList[0]
          } else {
            loading.close()
            this.loadPdf = false
            this.firstJoin = false
            return
          }
        }
        data.forEach((item, firstIndex) => {
          const treeDocList = item.treeDocList || []
          if (treeDocList.length < 1) {
            this.loadPdf = false
            // loading.close()
          }
          treeDocList.forEach(async (doc, index) => {
            const { fileId, id } = doc
            if (doc.id === (this.currentDocTemp && this.currentDocTemp.id || this.currentDoc.id)) {
              this.currentItem = item
              this.currentDocTemp = doc
              const isCommonDoc = item.treeName === '通用文书'
              doc.isCommonDoc = isCommonDoc
              doc.treeId = item.treeId
              this.docInfos[id] = doc
              this.docList.push(id)
              if (fileId === null) {
                await this.loadDocument({ id, firstIndex, index, loading, doc })
              } else {
                await this.transPdf({ loading, id, index, firstIndex })
              }
            }
          })
        })
      }
    },
    loadDocument ({ id, firstIndex, index, loading, doc }) {
      genDocument(id)
        .then((res) => {
          if (res.code === 0 && res.data !== null) {
            if (!this.currentDocId) {
              this.setCurStatus(id)
            }
            this.documentTree[firstIndex].treeDocList[index].fileId = res.data.fileId
            this.documentTree[firstIndex].treeDocList[index].ztFileId = res.data.ztFileId
            this.transPdf({ id, index, firstIndex, loading })
          } else {
            this.loadPdf = false
            loading.close()
            this.$set(this.docInfos[id], 'error', true)
            this.$message.error(this.documentTree[firstIndex].treeDocList[index].docName + `生成出错，请联系管理员!`)
          }
        })
        .catch(() => {
          this.loadPdf = false
          this.$set(this.docInfos[id], 'error', true)
          loading.close()
        })
    },
    // 文书列表
    // 判断当前定位状态
    setCurStatus (key) {
      const item = this.docInfos[key] || this.currentDocTemp
      const { id, isCommonDoc, treeId, docType } = item
      this.currentDocId = id
      if (isCommonDoc) {
        this.loadPersonType = 0
      } else {
        this.loadItemId = treeId
        this.loadPersonType = 1
      }
      if (docType === 'mp3' || docType === 'mp4' || docType === 'zip') {
        this.$message.warning(docType + '不支持签署')
        return
      }
      this.currentDocType = docType
      this.canInsert = true
    },
    loadAllEvidence () {
      const loading = this.$loading({
        lock: true,
        text: '拼命加载中...',
        spinner: 'el-icon-loading',
        background: 'transparent',
        target: this.$el
      })
      this.loadPdf = true
      this.currentDocType = -1
      this.evidenceList.forEach((evidence, index) => {
        if (!evidence.evidList.evidNum) {
          this.loadPdf = false
          loading.close()
        }
        evidence.evidList.forEach((evid, evidIndex) => {
          if (!evid.docNum) {
            this.loadPdf = false
            loading.close()
          }
          evid.docList.forEach((document, docIndex) => {
            if (['mp3', 'mp4', 'zip'].includes(document.docType)) {
              return
            }
            const { pdfFileId, id } = document
            document.isNotaryEvid = evidence.personName === '卷宗材料'
            this.evidenceInfos[id] = document
            this.evidenceArr.push(id)
            if (pdfFileId === null) {
              loading.text = '转换文档中...'
              transFileToPdf({ documentId: id, docType: this.currentDocType })
                .then((res) => {
                  if (res.code === 0 && res.data !== null) {
                    this.initPdfComponent(res.data, id, loading)
                    this.evidenceList[index].evidList[evidIndex].docList[docIndex].pdfFileId = res.data
                  } else {
                    this.loadPdf = false
                    loading.close()
                    this.$set(this.evidenceInfos[id], 'error', true)
                    this.$message.error(document.docName + res.message)
                  }
                })
                .catch(() => {
                  this.loadPdf = false
                  this.$set(this.evidenceInfos[id], 'error', true)
                  loading.close()
                })
            } else {
              this.initPdfComponent(pdfFileId, id, loading)
            }
          })
        })
      })
    },
    // 证据材料
    // 判断当前定位状态
    setCurEvidenceStatus (key) {
      const item = this.evidenceInfos[key]
      const { id, isNotaryEvid } = item
      this.currentDocId = id
      if (isNotaryEvid) {
        this.loadPersonType = 0
      } else {
        this.loadNotaryPersonId = id
        this.loadPersonType = 2
      }
      this.currentDocType = -1
      this.canInsert = true
    },
    handleFirstNameCheck (row) {
      row.checked = !row.checked
      row.treeDocList.forEach(item => { item.checked = row.checked })
      this.$forceUpdate()
    },
    handleNameCheck (parent, row) {
      row.checked = !row.checked
      parent.checked = parent.treeDocList.every(item => item.checked)
      this.$forceUpdate()
    },
    /* 证据材料- 第一层级勾选 */
    handleEvidFirstNameCheck (index) {
      const evidence = this.evidenceList[index] || []
      evidence.checked = !evidence.checked
      evidence.evidList.forEach(evid => {
        evid.checked = evidence.checked
        if (evid.docList) {
          evid.docList.forEach(document => {
            document.checked = evidence.checked
          })
        }
      })
      this.$forceUpdate()
    },
    /* 证据材料- 第二层级勾选 */
    handleEvidSecondNameCheck (evidence, evid) {
      this.$set(evid, 'checked', !evid.checked)
      if (evid.docList) {
        evid.docList.forEach(document => {
          document.checked = evid.checked
        })
      }
      evidence.checked = evidence.evidList.every(evid => evid.checked)
      this.$forceUpdate()
    },
    /* 证据材料- 第三层级勾选 */
    handleEvidThirdNameCheck (evidence, evid, document) {
      this.$set(document, 'checked', !document.checked)
      evid.checked = evid.docList.every(document => document.checked)
      evidence.checked = evidence.evidList.every(evid => evid.checked)
      this.$forceUpdate()
    },
    tabChange () {
      this.currentDocId = ''
      // this.docList = []
      // this.evidenceArr = []
      if (this.tabValue === 'file' && this.docList.length === 0) {
        this.loadAllDoc(this.documentTree)
      } else if (!this.evidenceArr.length) {
        this.loadAllEvidence()
      }
    },
    handlePopover (personId) {
      this.signVisible[personId] = {}
      this.signVisible[personId] = true
      const countdown = 2500
      const setinterval = () => {
        clearInterval(this.timer)
        this.signVisible[personId] = false
      }
      this.timer = setInterval(function () {
        setinterval()
      }, countdown)
    }
  }
}
</script>

<style scoped lang="scss">
.evid-wrap {
  height: calc(100% - 50px);
  padding: 10px;
  border: 1px solid #e6e6e6;
  overflow: auto;
}

.noTouch-signBtnBox {
  position: absolute;
  right: -35px;
  top: 50%;
  margin-top: -30px;
  display: flex;
  flex-direction: column;
  z-index: 0;

  .first-page {
    transform: rotate(180deg);
  }

  .el-button {
    margin: 10px 0;
  }

  .el-button.disabled {
    background: rgba(0, 0, 0, 0.1);
  }

  .page-text {
    width: 100%;
    margin-top: 5px;
    padding: 5px;
    display: inline-block;
    background: rgba(0, 0, 0, 0.1);
    text-align: center;
    color: #fff;
  }
}

.vdr.active {
  background: rgba(240, 242, 245, 0.5);
  border-radius: 10px;

  &::before {
    outline: none !important;
  }
}

.noTouch-signBox >>> .el-loading-mask {
  position: fixed;
}

#pdf_view_wrapper canvas[height] {
  float: left;
  height: 841px;
}

.files-canvas {
  overflow: hidden;
}

#pdf_view_wrapper canvas[height]:last-child {
  border-bottom: 1px dashed #000;
}

.no-touch-btn {
  align-items: center;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.evid-firstKey {
  flex-shrink: 1;
}

.evid-secondKey {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.tree-check-icon {
  float: left;
}

.evid-third {
  position: relative;
  padding-right: 20px;
  .complete {
    position: absolute;
    right: 5px;
    margin-right: 0;
  }
}

.complete {
  color: #67c23a;
  margin-right: -15px;
}
</style>
